package com.thf.util;

import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.errors.*;
import jdk.nashorn.internal.runtime.regexp.joni.exception.InternalException;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.rmi.ServerException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class Upload {
    private static final String URI = "http://192.168.145.128:9000";
    private static final String bucketName = "image";
    public static String file(MultipartFile ImgFile) throws IOException, InvalidKeyException, InvalidResponseException, InsufficientDataException, NoSuchAlgorithmException, ServerException, InternalException, XmlParserException, InvalidBucketNameException, ErrorResponseException, RegionConflictException, io.minio.errors.ServerException, io.minio.errors.InternalException {

        StringBuilder newName = new StringBuilder();
        newName.append(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS")))
                .append(RandomStringUtils.random(6,false,true))
                .append(".")
                .append(FilenameUtils.getExtension(ImgFile.getOriginalFilename()));
        MinioClient minioClient = MinioClient.builder().endpoint(URI)
                                                       .credentials("admin","123456789")
                                                       .build();
        PutObjectArgs args = PutObjectArgs.builder().stream(ImgFile.getInputStream(),ImgFile.getSize(),0)
                                                    .contentType(ImgFile.getContentType())
                                                    .bucket(bucketName)
                                                    .object(newName.toString())
                                                    .build();
        boolean isExist = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
        if(!isExist) {
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
        }
        minioClient.putObject(args);
        return  URI+ File.separator+bucketName+File.separator+newName;
    }

}
